import numpy as np
from collections import Counter
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
class KNNRegression:
    def __init__(self, k=3):
        self.k = k

    def fit(self, X_train, y_train):
        self.X_train = X_train
        self.y_train = y_train

    def predict(self, X_test):
        predictions = [self._predict(x) for x in X_test]
        return np.array(predictions)

    def _predict(self, x):
        # 计算待预测样本与所有训练样本之间的欧氏距离
        distances = np.sqrt(((self.X_train - x) ** 2).sum(axis = 1))

        # 获取距离最近的 k 个样本的索引
        k_indices = np.argsort(distances)[0:self.k]

        # 获取最近的 k 个样本的标签
        k_nearest_labels = y_train[k_indices]

        # 返回出现次数最多的标签
        ave_result = k_nearest_labels.mean()
        return ave_result


# 示例用法
if __name__ == "__main__":

    X,y = load_breast_cancer(return_X_y=True)
    X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.15)
    # 创建和训练 KNN 分类器
    knr = KNNRegression(k=3)
    knr.fit(X_train, y_train)

    # 进行预测
    predictions = knr.predict(X_test)
    print(predictions)  # 输出: [0 1]

    #评估
    print(mean_squared_error(predictions,y_test))